if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.CategoryModal = class CategoryModal {

    static categorySelect() { return document.getElementById('category-select'); }
    static modal() { return document.getElementById('category-modal'); }
    static title() { return xflib.client.CategoryModal.modal().querySelector('#modal-title'); }
    static categoryCodeInput() { return xflib.client.CategoryModal.modal().querySelector('#category-code'); }
    static categoryNameInput() { return xflib.client.CategoryModal.modal().querySelector('#category-name'); }

    constructor() {
        this.mode = 'info';
        this.modal = xflib.client.CategoryModal.modal();
        this.categorySelect = xflib.client.CategoryModal.categorySelect();
        this.initializeEventListeners();
    }

    initializeEventListeners() {
        xflib.client.CategoryModal.modal().querySelectorAll('.modal-close').forEach(btn => {
            btn.addEventListener('click', e => {
                if (this.modal) this.modal.style.display = 'none';
            });
        });

        const cancelButton = this.modal.querySelector('#cancel-button');
        cancelButton.addEventListener('click', () => {
            this.closeModal();
        });

        const saveButton = this.modal.querySelector('#save-button');
        saveButton.addEventListener('click', () => {
            this.saveCategory();
        });
    }

    closeModal() {
        this.modal.style.display = 'none';
    }

    openModal(mode, saveCallback, categoryCode = null, categoryName = null, cancelCallback = null) {
        this.mode = mode;

        if(!saveCallback) throw new Error('saveCallback is required');
        if (categoryCode === 'all') throw new Error('请选择需要编辑的分类');
        this.saveCallback = saveCallback;
        this.cancelCallback = cancelCallback || (() => {});

        if (mode === 'add') {
            xflib.client.CategoryModal.title().textContent = '分类 - 新增';
        } else if (mode === 'edit') {
            xflib.client.CategoryModal.title().textContent = '分类 - 编辑';
        } else {
            xflib.client.CategoryModal.title().textContent = '分类 - 查看';
        }

        xflib.client.CategoryModal.categoryCodeInput().value = categoryCode || '';
        xflib.client.CategoryModal.categoryNameInput().value = categoryName || '';

        this.modal.style.display = 'block';
    }

    saveCategory() {
        const categoryCode = xflib.client.CategoryModal.categoryCodeInput().value.trim();
        const categoryName = xflib.client.CategoryModal.categoryNameInput().value.trim();

        if (!categoryCode || !categoryName) {
            alert('分类代码和名称不能为空');
            return;
        }

        this.saveCallback(categoryCode, categoryName, this.mode).then(result => {
            this.closeModal();
        }).catch(error => {
            alert(error);
        });
    }
} 